package com.sgb.kjwl.view.ui.fragment.packers;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityFindPacksBinding;
import com.sgb.kjwl.model.entity.FindPackersEntity;
import com.sgb.kjwl.model.entity.packers.PickResultEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.NumberConstant;
import com.sgb.kjwl.view.ui.adapter.packers.FindPackersAdapter;
import com.sgb.kjwl.view.widget.PickPopWindow1;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.view.widget.ThreeLevelFilterWindow;
import com.sgb.kjwl.viewmodel.packers.FindPackersAtvModel;
import com.sgb.link.entity.PickFilterEntity;
import com.sgb.link.router.PathTeam;
import com.swgk.core.base.model.entity.SelectPopEntity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.customview.ScreenChildTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import static com.sgb.kjwl.utils.NumberConstant.TEAM_CONSTRUCTION;

/**
 * @author : younghow
 * @date : 2021/12/3 11:29
 * description:工队大厅
 */
public class WorkerTeamFragment extends AppLazyFragment {

    public static final int TEAM_GROUP = 1;

    private String mWorkOne,mWorkTwo,mWorkThree,mWorkName;

    public FindPackersAtvModel viewModel;

    private ActivityFindPacksBinding binding;
    private FindPackersAdapter findPackersAdapter;

    /**
     * 工程分类
     */
    private ThreeLevelFilterWindow popCategory;
    private PickResultEntity pickResultProject1;
    private PickResultEntity pickResultProject2;
    private PickResultEntity pickResultProject3;
    /**
     * 团队规模
     */
    private PickResultEntity pickResultTeamSize;
    /**
     * 所在区域
     */
    private ThreeLevelAreaWindow popCity;
    private PickResultEntity pickResultProvince;
    private PickResultEntity pickResultCity;
    private PickResultEntity pickResultArea;
    private String mAreaCode,mAreaName;

    private String publishTime;
    private int currentType;
    private boolean isLoadMore;

    public static WorkerTeamFragment newInstance(int type,String context, String workKindOne, String workKindThree, String workName, String publishTime) {
        WorkerTeamFragment intent = new WorkerTeamFragment();
        Bundle bundle = new Bundle();
        bundle.putString("workKindOne",workKindOne);
        bundle.putString("workKindTwo",context);
        bundle.putString("workKindThree",workKindThree);
        bundle.putString("workName",workName);
        bundle.putString("publishTime",publishTime);
        bundle.putInt("type",type);
        intent.setArguments(bundle);
        return (intent);
    }

    private void initFilterData(boolean isLoadMore) {
        this.isLoadMore = isLoadMore;
        viewModel.getNewList(getString(R.string.app_all).equals(pickResultTeamSize.getName())?"":pickResultTeamSize.getName(), pickResultProject1.getNo(),
                pickResultProject2.getNo(), pickResultProject3.getNo(), currentType + "",
                pickResultProvince.getNo(), pickResultCity.getNo(), pickResultArea.getNo(), isLoadMore,publishTime);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.activity_find_packs,container,false);
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        binding.setLifecycleOwner(this);
        viewModel = new ViewModelProvider(this).get(FindPackersAtvModel.class);

        if (getArguments() != null) {
            mWorkOne = getArguments().getString("workKindOne");
            mWorkTwo = getArguments().getString("workKindTwo");
            mWorkThree = getArguments().getString("workKindThree");
            mWorkName = getArguments().getString("workName");
            publishTime = getArguments().getString("publishTime");
            currentType = getArguments().getInt("type");
        }

        setTextButton();
        binding.sct.onSetCallPop(new ScreenChildTextView.ICallPop() {
            @Override
            public void openPop(int position, TextView content, LinearLayout bg, SelectPopEntity entity) {
                if (position == 0) {
                    showCategoryPop();
                } else if (position == 1) {
                    showCityPop();
                }
            }
        });

        if (findPackersAdapter == null) {
            if (currentType == TEAM_CONSTRUCTION) {
                findPackersAdapter = new FindPackersAdapter(getActivity(), null, Glide.with(this),true);
            } else  {
                findPackersAdapter = new FindPackersAdapter(getActivity(), null, Glide.with(this),false);
            }
        }
        findPackersAdapter.setOnItemClick(new AdapterOnItemClick<FindPackersEntity>() {
            @Override
            public void onItemClick(FindPackersEntity findPackersEntity, int position) {
                viewModel.getH5Url(findPackersEntity.getNo());
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(findPackersAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData(false);
            }

            @Override
            public void onLoadMore() {
                initFilterData(true);
            }
        });

        pickResultProject1 = new PickResultEntity();
        pickResultProject2 = new PickResultEntity();
        pickResultProject3 = new PickResultEntity();
        pickResultTeamSize = new PickResultEntity();
        pickResultProvince = new PickResultEntity();
        pickResultCity = new PickResultEntity();
        pickResultArea = new PickResultEntity();

        mAreaCode = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE,"");
        mAreaName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_NAME,"");

        if (!TextUtils.isEmpty(mWorkOne)){
            pickResultProject1.setNo(mWorkOne);
        }

        if (!TextUtils.isEmpty(mWorkTwo)){
            pickResultProject2.setNo(mWorkTwo);
            pickResultProject3.setNo(mWorkThree);
        }

        if (!TextUtils.isEmpty(mWorkName)){
            binding.sct.contentSelect(mWorkName,true,false,0);
        }

        initLiveData();
    }

    private void initLiveData() {

        viewModel.loading.observe(getViewLifecycleOwner(), aBoolean -> DialogHelper.showProgressDialog(getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false));

        viewModel.teamList.observe(getViewLifecycleOwner(), new Observer<List<FindPackersEntity>>() {
            @Override
            public void onChanged(List<FindPackersEntity> list) {
                if (isLoadMore) {
                    if (list != null && list.size() > 0) {
                        findPackersAdapter.addDatas(list);
                    }
                    binding.recyclerView.setNoMore(list.size() < 10);
                    binding.recyclerView.setVisibility(View.VISIBLE);
                } else {
                    binding.recyclerView.refreshComplete();
                    if (list != null && list.size() > 0) {
                        binding.emptyView.setVisibility(View.GONE);
                        findPackersAdapter.setDatas(list);
                        binding.recyclerView.smoothScrollToPosition(0);
                        if (list.size() < NumberConstant.NUMBER_TEN) {
                            binding.recyclerView.setNoMore(true);
                        }
                    } else {
                        findPackersAdapter.clearDatas();
                        binding.emptyView.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        viewModel.h5Url.observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                String[] split = s.split("----");
                ActivityJump.startActivity(PathTeam.TeamDetailActivity, Pair.create("no",split[1]),Pair.create("url",split[0]));
            }
        });

        viewModel.categoryType.observe(getViewLifecycleOwner(), new Observer<List<PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>>>>() {
            @Override
            public void onChanged(List<PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>>> pickFilterEntities) {
                if (popCategory == null) {
                    popCategory = new ThreeLevelFilterWindow(getActivity());
                    popCategory.setBgView(binding.grayLayout);
                    popCategory.setOnResultClick(new ThreeLevelFilterWindow.OnResultClick() {
                        @Override
                        public void result(Object key1, Object key2, Object key3) {
                            pickResultProject1.setNo(((PickResultEntity) key1).getNo());
                            pickResultProject1.setName(((PickResultEntity) key1).getName());
                            pickResultProject2.setNo(((PickResultEntity) key2).getNo());
                            pickResultProject2.setName(((PickResultEntity) key2).getName());
                            pickResultProject3.setNo(((PickResultEntity) key3).getNo());
                            pickResultProject3.setName(((PickResultEntity) key3).getName());
                            if (TextUtils.equals(getString(R.string.app_all), pickResultProject1.getName()) || TextUtils.equals("", pickResultProject1.getName())) {
                                binding.sct.contentSelect("工程分类",false,false,0);
                            } else {
                                if (TextUtils.equals(getString(R.string.app_all), pickResultProject2.getName())) {
                                    binding.sct.contentSelect(pickResultProject1.getName(),true,false,0);
                                } else {
                                    if (TextUtils.equals(getString(R.string.app_all), pickResultProject3.getName())) {
                                        binding.sct.contentSelect(pickResultProject2.getName(),true,false,0);
                                    } else {
                                        binding.sct.contentSelect(pickResultProject3.getName(),true,false,0);
                                    }
                                }
                            }
                            initFilterData(false);
                        }

                        @Override
                        public void reset() {
                            pickResultProject1.clear();
                            pickResultProject2.clear();
                            pickResultProject3.clear();
                            binding.sct.contentSelect("工程分类",false,false,0);
                            initFilterData(false);
                        }
                    });
                    popCategory.setOnDismissListener(() -> binding.sct.contentSelect(!"工程分类".equals(binding.sct.getName(0)),false,0));

                    if (!"".equals(pickResultProject1.getNo())){
                        popCategory.setThreeLevelDataForNormal(pickFilterEntities,mWorkOne,mWorkTwo,mWorkThree);
                    }else {
                        popCategory.setThreeLevelData(pickFilterEntities);
                    }
                }
            }
        });


        viewModel.city.observe(getViewLifecycleOwner(), new Observer<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
            @Override
            public void onChanged(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntities) {
                if (popCity == null) {
                    popCity = new ThreeLevelAreaWindow(getActivity()){
                        @Override
                        protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.provinceClick(baseAreaEntity, position);
                            pickResultProvince.setNo(baseAreaEntity.getNo());
                            pickResultProvince.setName(baseAreaEntity.getSimpleName());
                            if (getString(R.string.app_all).equals(baseAreaEntity.getSimpleName()) || pickResultProvince.getName().equals(baseAreaEntity.getSimpleName())){
                                pickResultCity.setNo("");
                                pickResultCity.setName("");
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.cityClick(baseAreaEntity, position);
                            pickResultCity.setNo(baseAreaEntity.getNo());
                            pickResultCity.setName(baseAreaEntity.getSimpleName());
                            if (getString(R.string.app_all).equals(baseAreaEntity.getSimpleName()) || pickResultCity.getName().equals(baseAreaEntity.getSimpleName())){
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void areaClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.areaClick(baseAreaEntity, position);
                            pickResultArea.setNo(baseAreaEntity.getNo());
                            pickResultArea.setName(baseAreaEntity.getSimpleName());
                        }

                        @Override
                        protected void reset() {
                            super.reset();
                            pickResultProvince.clear();
                            pickResultCity.clear();
                            pickResultArea.clear();
                            binding.sct.contentSelect("全部",true,false,1);
                            popCity.dismiss();
                            initFilterData(false);
                        }
                    };
                    popCity.setBgView(binding.grayLayout);
                    popCity.setProvinceSingle();
                    popCity.setCitySingle();
                    popCity.setAreaSingle();
                    popCity.setShowSimpleName(true);
                    pickResultProvince.setName(mAreaName);
                    popCity.setOnResultClick((key1, key2, key3) -> {
                        initFilterData(false);
                        if (!getString(R.string.app_all).equals(pickResultArea.getName())&&!"".equals(pickResultArea.getName())){
                            binding.sct.contentSelect(pickResultArea.getName(),true,false,1);
                            return;
                        }else {
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,1);
                        }

                        if (!getString(R.string.app_all).equals(pickResultCity.getName())&&!"".equals(pickResultCity.getName())){
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,1);
                            return;
                        }else {
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,1);
                        }

                        if (!getString(R.string.app_all).equals(pickResultProvince.getName())&&!"".equals(pickResultProvince.getName())){
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,1);
                        }else {
                            binding.sct.contentSelect("全部",true,false,1);
                        }
                    });
                    popCity.setOnDismissListener(() -> binding.sct.contentSelect(!"地区".equals(binding.sct.getName(1)),false,1));

                    popCity.setDataForAll(addressEntities,true,mAreaCode);
                }
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        pickResultProvince.setNo(mAreaCode);
        binding.sct.contentSelect(mAreaName,true,false,1);
        viewModel.getCategoryType();
        initFilterData(false);
        viewModel.getCityList();
    }


    /**
     * 工程-工程分类
     * @param
     */
    public void showCategoryPop() {
        binding.sct.contentSelect(false,true,0);
        popCategory.showPopwindow0(binding.sct);
    }

    /**
     * 省市区pop
     */
    public void showCityPop() {
        binding.sct.contentSelect(false,true,1);
        popCity.showPopwindow(binding.sct,0,0);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (NumberConstant.sIsBackForTeam == 1){
            initFilterData(false);
            NumberConstant.sIsBackForTeam = 0;
        }
    }

    private void setTextButton(){
        SelectPopEntity selectPopEntity3 = new SelectPopEntity("工程分类", "1", false, true);
        SelectPopEntity selectPopEntity1 = new SelectPopEntity("地区", "2", false, true);
        binding.sct.addTextButton(selectPopEntity3);
        binding.sct.addTextButton(selectPopEntity1);
    }
}
